import {messages} from "share/common";
import React,{Component} from 'react';
import {Modal, Button, Icon, Progress} from 'antd';

class FictitiousProgress extends Component{

  constructor(props){
    super(props);

    this.isStart = false;
    this.state = {
      currentProgress: 0,
    }
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.showDownloadModal && !this.isStart){
      this.startProgress();
      this.isStart = true;
    }
  }

  startProgress = () => {
    const {isFail, isCreated} = this.props;
    const {currentProgress} = this.state;
    let step = isCreated ? 30 : 5;
    if(currentProgress<=99 && !isFail){
      let pro = currentProgress + parseInt(Math.random() * step);
      pro = pro > 99 ? (isCreated ? 100 : 99) : pro;
      this.setState({
        currentProgress: pro,
      })
      setTimeout(this.startProgress,300);
    }
  }

  /**
   * 取消下载
   */
  onCancelDownload = () => {
    const {onCancel} = this.props;
    onCancel();
    this.setState({
      currentProgress: 0,
    },()=>{
      this.isStart = false;
    })
  }

  goToDownlond = () => {
    const {downloadUrl} = this.props;
    window.open(downloadUrl);
    this.onCancelDownload();
  }

  modalFooter = () => {
    const {currentProgress} = this.state;
    if(currentProgress === 100){
      return (
        <div style={{textAlign: 'right',marginTop:currentProgress === 100 ? 16 : 0}}>
          <Button type='primary' onClick={this.goToDownlond}>
            {messages('supplier-4.key1')/*下载*/}
          </Button>
          &nbsp;&nbsp;
          <Button onClick={this.onCancelDownload}>
            {messages('supplier-4.key2')/*关闭*/}
          </Button>
        </div>
      )
    }else{
      return (
        <div style={{textAlign: 'right'}}>
          <Button type='primary' onClick={this.onCancelDownload}>{messages('supplier-4.key3')/*取消下载*/}</Button>
        </div>
      )
    }
  }

  modalTitle = () => {
    const {currentProgress} = this.state;
    return currentProgress != 100 ? <h3>{messages('supplier-4.key4')/*数据加载中*/}...</h3> :
      <h3 style={{marginBottom: 16}}>
        <Icon type="check-circle" style={{color: 'green'}}/>{messages('supplier-4.key5')/*加载成功，请点击下载*/}
      </h3>;
  }

  render(){
    const {currentProgress} = this.state;
    const {showDownloadModal} = this.props;
    return (
      <div>
        <Modal
          visible={showDownloadModal}
          footer={null}
          closable={false}
        >
          {this.modalTitle()}
          <Progress percent={currentProgress} status="active"/>
          {currentProgress!=100 && <p>{messages('supplier-4.key6')/*请勿关闭或者离开当前页面，否则将导致下载失败*/}</p>}
          {this.modalFooter()}
        </Modal>
      </div>
    )
  }
}

/**
 * isFail  生成失败
 * isCreated  是否已经生成
 * downloadUrl  生成后的下载链接
 * showDownloadModal  弹框显示
 * onCancel  取消回调
 */

export default FictitiousProgress;
